<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/stores/user.js';
import { getUserShopAPI } from '@/apis/user.js';
import { getShopStatistics, getShopSalesRanking, getShopRevenueTrend, getShopOrderStatusStats } from '@/apis/shopApi.js';
import { ElMessage } from 'element-plus';

// 图表数据
const salesChartOption = ref({
  title: { 
    text: '商品销量排行',
    left: 'center'
  },
  tooltip: {},
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: { 
    type: 'value',
    name: '销量'
  },
  series: [{
    name: '销量',
    type: 'bar',
    data: [],
    itemStyle: {
      color: '#409EFF'
    }
  }]
});

const orderStatisticsOption = ref({
  title: { 
    text: '订单统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: 'bottom'
  },
  series: [{
    name: '订单状态',
    type: 'pie',
    radius: ['40%', '70%'],
    avoidLabelOverlap: false,
    itemStyle: {
      borderRadius: 10,
      borderColor: '#fff',
      borderWidth: 2
    },
    label: {
      show: false,
      position: 'center'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: '18',
        fontWeight: 'bold'
      }
    },
    labelLine: {
      show: false
    },
    data: []
  }]
});

const revenueChartOption = ref({
  title: { 
    text: '收入趋势',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: { 
    type: 'value',
    name: '收入 (元)'
  },
  series: [{
    name: '收入',
    type: 'line',
    data: [],
    itemStyle: {
      color: '#F56C6C'
    },
    smooth: true
  }]
});

const shopData = ref({
  shopName: '',
  shopAvatar: ''
});

const statsOverview = ref({
  totalOrders: 0,
  totalRevenue: 0,
  totalProducts: 0,
  averageRating: 0
});

onMounted(() => {
  loadShopInfo();
  loadStatsOverview();
  loadChartData();
});

const loadShopInfo = async () => {
  try {
    const res = await getUserShopAPI(useUserStore().userInfo.uid);
    if (res.code === 200) {
      shopData.value = res.data;
    } else {
      ElMessage.error('获取店铺信息失败');
    }
  } catch (error) {
    ElMessage.error('获取店铺信息失败: ' + error.message);
  }
};

const loadStatsOverview = async () => {
  try {
    // 先获取店铺信息
    const shopRes = await getUserShopAPI(useUserStore().userInfo.uid);
    if (shopRes.code === 200) {
      // 再获取统计数据
      const statRes = await getShopStatistics(shopRes.data.shopId);
      if (statRes.code === 200) {
        statsOverview.value.totalOrders = statRes.data.totalOrders || 0;
        statsOverview.value.totalRevenue = statRes.data.totalRevenue || 0;
        statsOverview.value.totalProducts = statRes.data.totalProducts || 0;
        statsOverview.value.averageRating = 4.8; // 这个数据需要从后端获取，暂时写死
      } else {
        ElMessage.error('获取统计数据失败');
      }
    }
  } catch (error) {
    ElMessage.error('获取统计数据失败: ' + error.message);
  }
};

const loadChartData = async () => {
  try {
    // 获取店铺信息
    const shopRes = await getUserShopAPI(useUserStore().userInfo.uid);
    if (shopRes.code === 200) {
      const shopId = shopRes.data.shopId;
      
      // 获取商品销量排行
      const salesRes = await getShopSalesRanking(shopId);
      if (salesRes.code === 200) {
        const names = salesRes.data.map(item => item.name);
        const values = salesRes.data.map(item => item.value);
        
        salesChartOption.value.xAxis.data = names;
        salesChartOption.value.series[0].data = values;
      }
      
      // 获取收入趋势
      const revenueRes = await getShopRevenueTrend(shopId);
      if (revenueRes.code === 200) {
        const months = revenueRes.data.map(item => item.month);
        const revenues = revenueRes.data.map(item => item.revenue);
        
        revenueChartOption.value.xAxis.data = months;
        revenueChartOption.value.series[0].data = revenues;
      }
      
      // 获取订单状态统计
      const orderStatusRes = await getShopOrderStatusStats(shopId);
      if (orderStatusRes.code === 200) {
        orderStatisticsOption.value.series[0].data = orderStatusRes.data;
      }
    }
  } catch (error) {
    ElMessage.error('获取图表数据失败: ' + error.message);
  }
};

const formatCurrency = (amount) => {
  return '¥' + amount.toFixed(2);
};
</script>

<template>
<div class="dataPanel">
  <div class="shop-header">
    <img :src="shopData.shopAvatar || 'https://via.placeholder.com/60x60?text=店铺'" alt="店铺头像" class="shop-avatar">
    <h2>{{ shopData.shopName || '我的店铺' }} - 数据统计</h2>
  </div>
  
  <div class="stats-overview">
    <el-row :gutter="20">
      <el-col :span="5">
        <div class="stat-card">
          <div class="stat-value">{{ statsOverview.totalOrders }}</div>
          <div class="stat-label">总订单数</div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="stat-card">
          <div class="stat-value">{{ formatCurrency(statsOverview.totalRevenue) }}</div>
          <div class="stat-label">总收入</div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="stat-card">
          <div class="stat-value">{{ statsOverview.totalProducts }}</div>
          <div class="stat-label">商品数量</div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="stat-card">
          <div class="stat-value">{{ statsOverview.averageRating }}</div>
          <div class="stat-label">平均评分</div>
        </div>
      </el-col>
    </el-row>
  </div>
  
  <div class="charts-container">
    <e-charts :option="salesChartOption" class="chart" />
    <e-charts :option="revenueChartOption" class="chart" />
    <e-charts :option="orderStatisticsOption" class="chart" />
  </div>
</div>
</template>

<style scoped lang="less">
.dataPanel {
  width: 100%;
  max-width: 1200px;
  min-height: 400px;
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

.shop-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  
  .shop-avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    margin-right: 20px;
    object-fit: cover;
  }
  
  h2 {
    margin: 0;
    color: #333;
    font-size: 24px;
  }
}

.stats-overview {
  margin-bottom: 30px;
  
  .stat-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 10px;
    padding: 20px;
    text-align: center;
    color: white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s;
    
    &:hover {
      transform: translateY(-5px);
    }
    
    .stat-value {
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 5px;
    }
    
    .stat-label {
      font-size: 14px;
      opacity: 0.9;
    }
  }
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr;
  gap: 30px;
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: 300px;
  background-color: #fafafa;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

@media (max-width: 768px) {
  .stats-overview .el-col {
    margin-bottom: 15px;
  }
}

</style>